package cn.com.dhcc.ddi.task.service;

import cn.com.dhcc.app.core.annotation.SiColumn;
import cn.com.dhcc.app.core.annotation.SiColumn.DB_TYPE_GROUP;

import java.text.ParseException;
import java.text.SimpleDateFormat;


public class DbTypeConvertUtils {
	
	private static ThreadLocal<SimpleDateFormat> timeFormat=new ThreadLocal<SimpleDateFormat>(){
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");//时间戳
		}
	};
			
	private static ThreadLocal<SimpleDateFormat> dateFormat=new ThreadLocal<SimpleDateFormat>(){
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期
		}
	};

	/**
	 * 数据库字段类型转换
	 * @param type 字段类型
	 * @param value  字段值
	 * @return
	 * @throws ParseException 
	 */
	public static Object convert(String type,String value) throws ParseException{
		//判断是否是字符串类型
		DB_TYPE_GROUP group = DB_TYPE_GROUP.getTypeGroup(type);
		if (SiColumn.DB_TYPE_GROUP.STR == group) {
			return value;
		}else if(DB_TYPE_GROUP.TIMESTAMP == group){
			return timeFormat.get().parse(value);
		}else if(DB_TYPE_GROUP.DATE == group){
			return dateFormat.get().parse(value);
		}
		return value;
	}


	private static boolean contain(String type,SiColumn.DB_TYPE_GROUP grup){
		DB_TYPE_GROUP[] groups = grup.values();
		for (DB_TYPE_GROUP group : groups) {
			String[] dbTypes = group.getDbType();
			for (String dbType : dbTypes) {
				if (type.toLowerCase().startsWith(dbType)) {
					return true;
				}
			}
		}
		return false;
	}
}
